package com.bright.cwduijie.duijie.service.impl;

import cn.cloudlizard.jtzc.JtzcSDK;
import cn.cloudlizard.jtzc.config.AppClientConfig;
import cn.cloudlizard.jtzc.config.JtzcServerConfig;
import cn.cloudlizard.jtzc.exception.JtzcSDKException;
import cn.cloudlizard.jtzc.model.req.SyncFileReq;
import cn.cloudlizard.jtzc.model.resp.Result;
import cn.cloudlizard.jtzc.model.resp.SyncTaskRes;
import cn.hutool.core.io.IORuntimeException;
import cn.hutool.http.HttpException;
import com.bright.cwduijie.duijie.constant.ConfigConstants;
import com.bright.cwduijie.duijie.enums.DataApi;
import com.bright.cwduijie.duijie.enums.SJJHBZ;
import com.bright.cwduijie.duijie.manager.DuijieManager;
import com.bright.cwduijie.duijie.pojo.dto.QueryTaskDto;
import com.bright.cwduijie.duijie.pojo.dto.QueryTaskReturnDto;
import com.bright.cwduijie.duijie.pojo.dto.SendDataReturnDto;
import com.bright.cwduijie.duijie.pojo.dto.SendFileDto;
import com.bright.cwduijie.duijie.service.WebExchangeService;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;
import java.io.InterruptedIOException;
import java.net.SocketTimeoutException;
import java.util.*;
import java.util.concurrent.CompletionException;

/**
 * @Author hxj
 * @Date 2024/7/5 10:39
 * @Description
 */

@Qualifier("normal")
@Component
@RequiredArgsConstructor
@Slf4j
public class WebExchangeServiceImpl implements WebExchangeService {

//    private final RestTemplate restTemplate;

    private final ObjectMapper objectMapper;

    private final ConfigConstants constant;

    public SendDataReturnDto sendData(Object data, String serviceCode) {

//        Map<String, Object> sendDataMap = new HashMap<>();
//        sendDataMap.put("DATA", data);

        String dataStr;
        try {
            dataStr = objectMapper.writeValueAsString(data);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
        return sendData(dataStr, serviceCode);

    }

    @Override
    public SendDataReturnDto sendData(String dataString, String serviceCode) {
//        log.info("请求加密前：" + dataString);


        JtzcSDK sdk = getJtzcSDK();

        Result<SyncTaskRes> syncTaskResResult = sdk.syncData(serviceCode, dataString);
        SendDataReturnDto sendDataDto = new SendDataReturnDto();
        sendDataDto.setIsSuccess(syncTaskResResult.isSuccess());
        sendDataDto.setErrorCode(syncTaskResResult.getErrorCode());
        sendDataDto.setMessage(syncTaskResResult.getErrorMsg());
        SyncTaskRes data = syncTaskResResult.getData();
        sendDataDto.setTaskId(data.getTASK_ID());

        return sendDataDto;
    }

    private JtzcSDK getJtzcSDK() {

//        log.debug("开始获取SDK");
        JtzcSDK sdk = new JtzcSDK(
                new JtzcServerConfig(constant.getDomain(), constant.getRootPath(), constant.getJtzcPublicKey(),
                        3 * 1000, 10 * 1000),
                new AppClientConfig(constant.getAppId(), constant.getAppSecret(), constant.getAppSecretIV(), constant.getAppPrivateKey())
        );
//        log.debug("获取SDK结束");
        return sdk;
    }

    @Override
    public SendDataReturnDto sendFile(SendFileDto sendFileDto, String serviceCode) throws IOException {

        JtzcSDK sdk = getJtzcSDK();

        Result<SyncTaskRes> syncTaskResResult = sdk.syncFile(serviceCode,
                new SyncFileReq(sendFileDto.getDataKey(), sendFileDto.getTyshxydm(), sendFileDto.getBusinessDataKey(),
                        sendFileDto.getFile(), sendFileDto.getFileDateTime(), sendFileDto.getFileName()));
        SendDataReturnDto sendDataDto = new SendDataReturnDto();
        sendDataDto.setIsSuccess(syncTaskResResult.isSuccess());
        sendDataDto.setErrorCode(syncTaskResResult.getErrorCode());
        sendDataDto.setMessage(syncTaskResResult.getErrorMsg());
        SyncTaskRes data = syncTaskResResult.getData();
        sendDataDto.setTaskId(data.getTASK_ID());

        return sendDataDto;

    }

    @Override
    public List<QueryTaskReturnDto> queryTask(QueryTaskDto queryTaskDto) {

        List<String> taskIds = queryTaskDto.getTaskIds();
        Map<String, Object> dataMap = new HashMap<>();
        dataMap.put("TASK_IDS", taskIds);
        String dataJson = null;
        try {
            dataJson = objectMapper.writeValueAsString(dataMap);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }

        JtzcSDK sdk = getJtzcSDK();
        Result<List<SyncTaskRes>> result;
        try {
            result = sdk.queryTask(DataApi.QUERY_TASK.getServiceCode(), dataJson);
        } catch (JtzcSDKException e) {
            log.error("查询任务网络连接超时：" + e.getMessage());
            return null;
        }
        Boolean success = result.isSuccess();
        if (!success) {
            log.error("查询异步任务结果失败：" + taskIds + ", " + result.getErrorCode() + ", " + result.getErrorMsg());
            return null;
        }

        List<SyncTaskRes> taskResList = result.getData();
//        List<SendDataReturnDto> returnValue = new ArrayList<>(taskResList.size());
        List<QueryTaskReturnDto> returnValue = new ArrayList<>(taskResList.size());

        for (SyncTaskRes syncTaskRes : taskResList) {
            QueryTaskReturnDto dto = new QueryTaskReturnDto();
            dto.setTaskId(syncTaskRes.getTASK_ID());
            // 识别任务状态
            Byte task_state = syncTaskRes.getTASK_STATE();
            int state = task_state.intValue();
            dto.setTaskState(state);
            int sjjhbz;
            String message;
            switch (state) {
                case 1:
//                    sjjhbz = SJJHBZ.EXECUTING.getValue();
//                    message = "等待中";
                    // 20240718 省平台采用快速反馈模式 返回这个就是已接收 校验结果没返回 但可以继续往下推下一批次数据
                    sjjhbz = SJJHBZ.FEEDBACK_BUT_NOT_CHECK_COMPLETE.getValue();
                    message = SJJHBZ.FEEDBACK_BUT_NOT_CHECK_COMPLETE.getDescription();
                    break;
                case 2:
                    sjjhbz = SJJHBZ.EXECUTING.getValue();
                    message = "执行中";
                    log.debug(syncTaskRes.getTASK_ID() + "返回taskState=2");
                    break;
                case 3:
                    sjjhbz = SJJHBZ.SUCCESS.getValue();
                    message = SJJHBZ.SUCCESS.getDescription();
                    break;
                case 4:
                    sjjhbz = SJJHBZ.ERROR.getValue();
                    message = "服务端异常：" + syncTaskRes + ", TASK_STATE=" + state;
                    break;
                case 5:
                    sjjhbz = SJJHBZ.ERROR.getValue();
                    message = "业务失败：" + syncTaskRes.getTASK_FAIL_MSG() + ", TASK_STATE=" + state;
                    break;
                default:
//                    log.debug("返回的任务状态不在规定范围内：" + state);
//                    continue;
                    sjjhbz = SJJHBZ.ERROR.getValue();
                    message = "返回的任务状态不在规定范围内：" + syncTaskRes + ", TASK_STATE=" + state;
                    break;
            }
            dto.setSjjhbz(sjjhbz);
            dto.setMessage(message);

            returnValue.add(dto);
        }

        return returnValue;
    }




}
